/*
 * @Description: 
 * @Author: zyj
 * @Date: 2022-05-27 17:11:22
 * @LastEditors: zyj
 * @LastEditTime: 2022-06-10 11:50:34
 */
/* 柯里化 */
function curring(fn) {
  return function (...args) {
    return function (...userArgs) {
      return fn(...args, ...userArgs)
    }
  }
}


function isType(type, val) {
  return Object.prototype.toString.call(val) == `[object ${type}]`;
}


let util = {};
['String', 'Number', 'Boolean', 'Null', 'Undefined', 'Array', 'Object'].forEach((type) => {
  util[`is${type}`] = curring(isType)(type);
})
console.log(util.isNumber(123));
console.log(util.isNumber("123"));


function sum(a, b, c, d) {
  console.log(a, b, c, d);
}


function curring(fn) {
  const exec = (args = []) => {
    return args.length >= fn.length ? fn(args) : (...userArgs) => exec([...args, ...userArgs]);
  }
  return exec();
}

curring(sum)(1)(2, 3, 4);
curring(sum)(1)(2)(3, 4);
curring(sum)(1)(2, 3)(4);

/* 场景：要计算一个月30天的营业额，前29天每天的金额都先存储，在第30天时计算总和*/
const curry2 = function (fn) {
  let arg = [];
  return function () {
    if (arguments.length == 0) {
      return fn.apply(this, arg)
    } else {
      [].push.apply(arg, arguments);
      return arguments.callee;
    }
  }
}

let cost = (function () {
  let total = 0;
  return function () {
    for (let i = 0; i < arguments.length; i++) {
      total += arguments[i]
    }
    return total
  }
})()

cost = curry2(cost);
cost(100);
cost(200);
cost(300);
cost(400);
console.log(cost());
